﻿#include "mainwindow.h"
#include "emojichoose.h"
#include "ui_mainwindow.h"

#include <QJsonArray>
#include <QJsonObject>
#include <QMessageBox>
#include <QJsonDocument>
#include <QFile>
#include <QStringList>
#include <QPixmap>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    net = NetworkConnect::connectserver();
    server = net->getconserver();
    connect(net, SIGNAL(getfriendslist(QByteArray)),
            this, SLOT(flashfriendslist(QByteArray)));

    connect(net, SIGNAL(forwardmsg(QByteArray)),
            this, SLOT(handle_forwardmsg(QByteArray)));

    connect(net, &NetworkConnect::newclient,
            this, &MainWindow::on_pushButton_flash_clicked);

    on_pushButton_flash_clicked();
}

QLabel *MainWindow::getlabel_id() const
{
    return ui->label_id;
}

QLabel *MainWindow::getlabel_name() const
{
    return ui->label_name;
}

void MainWindow::setuserid(const QString &userid)
{
    this->userid = userid;
}

MainWindow::~MainWindow()
{
    delete ui;
    net->destroyThis();
}


void MainWindow::on_pushButton_flash_clicked()
{
    QJsonObject obj;
    obj.insert("command", "getfriendslist");
    server->write(QJsonDocument(obj).toJson());
}

/*
 * {
 * "type" : "getfriendslist"
 *  "users" : {
 *  	userid1 : username1
 *  }
 *
 * }
 *
 * */
//刷新在线用户
void MainWindow::flashfriendslist(QByteArray mess)
{
//    qDebug() << "触发刷新好友列表槽函数" << mess;
    QJsonDocument js = QJsonDocument::fromJson(mess);
    QJsonObject obj = js.object().value("users").toObject();

    QStringList useridlist = obj.keys();
    for(int i = 0; i < useridlist.size(); i++)
    {
        QString tmp = useridlist[i];
        useridlist[i].append("::");
        useridlist[i].append(obj.value(tmp).toString());
    }
    ui->listWidget_friend->clear();
    ui->listWidget_friend->addItems(useridlist);
}


void MainWindow::on_pushButton_send_clicked()
{
    QString sendmsg = ui->textEdit_editmess->toPlainText();
    if(sendmsg.isEmpty())
    {
        qDebug() << "没有输入内容";
        return;
    }
    ui->textEdit_editmess->clear();
    QListWidgetItem *curitem = ui->listWidget_friend->currentItem();
    if(curitem == nullptr)
    {
        QMessageBox::warning(this, "没有选择列表", "请刷新列表或者选择发送目标");
        return;
    }

    QString oldtext = ui->label_showmess->text();
    ui->label_showmess->setText(oldtext + "\n" + "我:" +sendmsg);//写进当前

    QString recver = curitem->text();
    recver = recver.split("::")[0];
    QJsonObject sendobj;
    sendobj.insert("command", "sendmessage");
    sendobj.insert("msgtype", "normalmsg");
    sendobj.insert("sender", userid);
    sendobj.insert("recver", recver);
    sendobj.insert("message", sendmsg);

    server->write(QJsonDocument(sendobj).toJson());
}

void MainWindow::handle_forwardmsg(QByteArray mess)
{
    QJsonObject obj = QJsonDocument::fromJson(mess).object();
    QString msg = obj.value("message").toString();
    QString msgtype = obj.value("msgtype").toString();
    QString emojipic = obj.value("message").toString();
    emojipic = QString(":/emoji/OIP%1.jpg").arg(emojipic.remove("emoji@"));//
    if(msgtype == "emoji")
    {
        QMessageBox *emojiWindow = new QMessageBox (this);
        QPixmap emojipixmap(emojipic);
        emojiWindow->setIconPixmap(emojipixmap);
        emojiWindow->exec();
        return;
    }
    if(msg.isEmpty())
    {
        qDebug() << "空消息";
        return;
    }
    QString oldtext = ui->label_showmess->text();
    QString newtext = oldtext.append("\n")
            .append(obj.value("sender").toString())
            .append("::").append(obj.value("message").toString());

    ui->label_showmess->setText(newtext);
}


void MainWindow::on_listWidget_friend_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if(current == nullptr)
    {
        qDebug() << "空指针";
        return;
    }
    if(previous == nullptr)
    {
        QString newtext = current->text().split("::").at(0);
        QFile newfile(newtext, this);
        if(!newfile.open(QIODevice::ReadWrite))
        {
            qDebug() << "打开文件" << newtext << "失败";
            return;
        }
        ui->label_showmess->setText(newfile.readAll());
        return;
    }
    if(current == previous)
    {
        qDebug() << "相同指针";
        return;
    }
    QString oldtext = previous->text().split("::").at(0);
    QString newtext = current->text().split("::").at(0);

    QFile oldfile(oldtext, this);
    QFile newfile(newtext, this);

    QString tobesave = ui->label_showmess->text();

    if(!newfile.open(QIODevice::ReadWrite))
    {
        qDebug() << "打开文件" << newtext << "失败";
        return;
    }
    ui->label_showmess->setText(newfile.readAll());

    if(tobesave.isEmpty())
    {
        return;
    }

    if(!oldfile.open(QIODevice::ReadWrite | QIODevice::Truncate))
    {
        qDebug() << "打开文件" << oldtext << "失败";
        return;
    }

    oldfile.write(tobesave.toUtf8());
    oldfile.flush();
}


void MainWindow::on_pushButton_emoji_clicked()
{
    emojichoose *w = new emojichoose (this);
    w->setAttribute(Qt::WA_DeleteOnClose);
    w->show();

    connect(w->getButtonGroup(), SIGNAL(idClicked(int)),
            this, SLOT(emojiChosenHandle(int)));//连接表情包选择窗口的选择信号
}

void MainWindow::emojiChosenHandle(int id)
{
    QListWidgetItem *curitem = ui->listWidget_friend->currentItem();
    if(curitem == nullptr)
    {
        QMessageBox::warning(this, "没有选择列表", "请刷新列表或者选择发送目标");
        return;
    }

    QString recver = curitem->text();
    recver = recver.split("::")[0];

    QJsonObject obj;
    obj.insert("command", "sendmessage");
    obj.insert("msgtype", "emoji");
    obj.insert("sender", userid);
    obj.insert("recver", recver);
    obj.insert("message", QString("emoji@%1").arg(id - 1));// 按钮的id从1开始， 表情包的id从0开始

    server->write(QJsonDocument(obj).toJson());
}

